package cn.snowsoft.iot.module.warning.controller.admin.home;

import cn.hutool.core.bean.BeanUtil;
import cn.snowsoft.iot.framework.common.pojo.CommonResult;
import cn.snowsoft.iot.module.cps.api.equipment.AdminEquipmentApi;
import cn.snowsoft.iot.module.cps.api.equipment.dto.EquipmentRelateWarningDTO;
import cn.snowsoft.iot.module.warning.controller.admin.home.vo.*;
import cn.snowsoft.iot.module.warning.dal.dataobject.home.HomeDO;
import cn.snowsoft.iot.module.warning.dal.dataobject.warning.config.WarningDO;
import cn.snowsoft.iot.module.warning.service.warning.action.IWarningActionService;
import cn.snowsoft.iot.module.warning.service.warning.config.IWarningService;
import cn.snowsoft.iot.module.warning.service.warning.record.IWarningRecordService;
import cn.snowsoft.iot.module.warning.service.warning.rule.IWarningRuleService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Tag(name = "管理后台 - 首页")
@RestController
@RequestMapping("/warning/home")
public class HomeController {

    @Autowired
    private IWarningRecordService recordService;

    @Autowired
    private IWarningRuleService ruleService;

    @Autowired
    private IWarningActionService actionService;

    @Autowired
    private IWarningService warningService;

    @Autowired
    private AdminEquipmentApi equipmentApi;



    @GetMapping("/count")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "获取告警相关数据")
    public CommonResult<HomeDO> getCount () {
        HomeDO homeDO = new HomeDO();

        Integer ruleCount = ruleService.getRuleCount();
        Map<String, Long> map = new HashMap<>();
        List<WarningDO> warningDOS = warningService.list();

        Map<String, Long> stringLongMap = Optional.ofNullable(warningDOS).orElse(new ArrayList<>()).stream().collect(Collectors.groupingBy(WarningDO::getWarningType, Collectors.counting()));
        Long conditions = stringLongMap.get("1");

        Long timing = stringLongMap.get("2");

        Long manualOperation = stringLongMap.get("3");

        map.put("conditions", ObjectUtils.isNotEmpty(conditions)?conditions:0);
        map.put("timing", ObjectUtils.isNotEmpty(timing)?timing:0);
        map.put("manualOperation", ObjectUtils.isNotEmpty(manualOperation)?manualOperation:0);


        List<ActionTypeCountVO> actionType = actionService.getActionTypeCount();
        Integer actionCount = 0;
        for (ActionTypeCountVO actionTypeCountVO : actionType) {
            actionCount += actionTypeCountVO.getActionCount();
        }

        Integer configCount = warningService.getConfifCount();
        Integer configEnableCount = 0;
        Integer configDisableCount = 0;
        List<WarningConfigStatusVO> configStatusList = warningService.getStatusCount();
        for (WarningConfigStatusVO warningConfigStatusVO : configStatusList) {
            if (warningConfigStatusVO.getIsEnable() == 1) {
                configEnableCount += warningConfigStatusVO.getCount();
            } else {
                configDisableCount += warningConfigStatusVO.getCount();
            }
        }

        List<RecordVO> recordDOS = recordService.getRecordList();

        List<String> keyList = new ArrayList<>();
        List<Integer> valueList = new ArrayList<>();
        Map<LocalDate, Integer> dailyAlertCount = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDate startDate = now.minusDays(6).toLocalDate();


        for (LocalDate date = startDate; !date.isAfter(now.toLocalDate()); date = date.plusDays(1)) {
            dailyAlertCount.put(date, 0);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        for (RecordVO record : recordDOS) {
            LocalDate alertDate = record.getCreateTime().toLocalDate();
            if (dailyAlertCount.containsKey(alertDate)) {
                dailyAlertCount.put(alertDate, dailyAlertCount.get(alertDate) + 1);
            }
        }


        List<Map.Entry<LocalDate, Integer>> sortedEntries = new ArrayList<>(dailyAlertCount.entrySet());
        sortedEntries.sort(Comparator.comparing(Map.Entry::getKey));

        for (Map.Entry<LocalDate, Integer> entry : sortedEntries) {
            keyList.add(entry.getKey().format(formatter));
            valueList.add(entry.getValue());
        }
        

        homeDO.setRuleCount(ruleCount);
        homeDO.setActionCount(actionCount);
        homeDO.setConfigCount(configCount);
        homeDO.setConfigEnableCount(configEnableCount);
        homeDO.setConfigDisableCount(configDisableCount);
        homeDO.setRecordCount(recordDOS.size());
        homeDO.setTimeList(keyList);
        homeDO.setWarningCountList(valueList);


        homeDO.setActionType(actionType);
        homeDO.setUseCountMap(map);

        return CommonResult.success(homeDO);
    }


    @GetMapping("/getEquipmentRelateWarning")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "获取设备关联告警数")
    public CommonResult<List<EquipmentRelateWarningDTO>> getEquipmentRelateWarning() {
        List<EquipmentRelateWarningVO> equipmentIds = warningService.getEquipmentRelateWarning();
        List<EquipmentRelateWarningDTO> equipmentRelateWarningDTOS = new ArrayList<>();
        for (EquipmentRelateWarningVO equipmentId : equipmentIds) {
            EquipmentRelateWarningDTO relateWarningDTO = new EquipmentRelateWarningDTO();
            relateWarningDTO.setWarningCount(equipmentId.getWarningCount());
            relateWarningDTO.setEquipmentId(equipmentId.getEquipmentId());
            equipmentRelateWarningDTOS.add(relateWarningDTO);
        }
        List<EquipmentRelateWarningDTO> equipmentDetail = equipmentApi.getEquipmentDetail(equipmentRelateWarningDTOS);
        return CommonResult.success(equipmentDetail);
    }
}
